//
//  SJAPP.swift
//  SJSwiftKit
//
//  Created by swordjoy on 2017/2/16.
//  Copyright © 2017年 swordjoy. All rights reserved.
//

import UIKit
import MBProgressHUD
import CoreTelephony

/// APP代理
public let appDelegate_sj: UIApplicationDelegate? = UIApplication.shared.delegate

/// 国际化字符串
///
/// - Parameter key: 字符串key
/// - Returns: 国际化字符串
public func NSLocalizedString(_ key: String) -> String {
  return NSLocalizedString(key, comment: "")
}

typealias VoidClosure = ( () -> Void )
typealias DoubleStringVoidClosure = ( (String, String) -> Void )

public struct SJApp {
  
  // MARK: - property
  
  private static let SJAppHasBeenOpened = "SJAppHasBeenOpened"
  
  /// 获取APP name
  public static var name: String = {
    return SJApp.stringFromInfoDictionary(forKey: "CFBundleDisplayName")
  }()
  
  /// 获取APP 版本号
  public static var version: String = {
    return SJApp.stringFromInfoDictionary(forKey: "CFBundleShortVersionString")
  }()
  
  /// 获取APP Build号
  public static var build: String = {
    return SJApp.stringFromInfoDictionary(forKey: "CFBundleVersion")
  }()
  
  /// 获取APP 项目名
  public static var executable: String = {
    return SJApp.stringFromInfoDictionary(forKey: "CFBundleExecutable")
  }()
  
  /// 获取APP Bundle ID
  public static var bundle: String = {
    return SJApp.stringFromInfoDictionary(forKey: "CFBundleIdentifier")
  }()
  
  public static var keyWindow: UIWindow = {
    return UIApplication.shared.keyWindow!
  }()
  
  private static func stringFromInfoDictionary(forKey key: String) -> String {
    guard let infoDictionary = Bundle.main.infoDictionary, let value = infoDictionary[key] as? String else {
      return ""
    }
    
    return value
  }
  
//  public static var isNetWork: Bool {
//    
//    return Reachability.forInternetConnection().isReachable()
//
//    
//  }
  
  
  // MARK: - 路径
  
  
  
  // MARK: - Function
  
  /// debug执行
  ///
  /// - Parameter block: debug环境下执行的闭包代码
  public static func debug(_ block: () -> Void) {
    #if DEBUG
      block()
    #endif
  }
  
  /// 发布版本执行
  ///
  /// - Parameter block: 发布环境下执行的闭包代码
  public static func release(_ block: () -> Void) {
    #if !DEBUG
      block()
    #endif
  }
  
  
  /// 判断某个版本APP是否第一次运行
  ///
  /// - Parameter version: APP版本 默认为设置版本
  /// - Returns: 布尔值
  public static func isFirstStart(version: String = SJApp.version) -> Bool {
    let key: String
    if version == "" {
      key = SJAppHasBeenOpened
    } else {
      key = SJAppHasBeenOpened + "\(version)"
    }
    
    let defaults = UserDefaults.standard
    let hasBeenOpened: Bool = defaults.bool(forKey: key)
    
    return !hasBeenOpened
  }
  
  /// 如果该版本第一次进入,执行闭包代码
  ///
  /// - Parameter closure: 该版本第一次进入时,执行的闭包代码
  public static func onFirstStart(_ closure: () -> Void ) {
    let  key = SJAppHasBeenOpened + "\(version)"
    
    let defaults = UserDefaults.standard
    let hasBeenOpened: Bool = defaults.bool(forKey: key)
    if hasBeenOpened != true {
      defaults.set(true, forKey: key)
      closure()
    }
  }
}

// MARK: - 路径

extension SJApp {
  
  public static var homeDirectory: String {
    return NSHomeDirectory()
  }
  
  // 会同步iTunes
  public static var documents: String {
    return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
  }
  
  // Library/Cache 不会同步iTunes
  public static var caches: String {
    return NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first!
  }
  
  public static var cachesURL: URL {
    return URL(fileURLWithPath: SJApp.caches)
  }

  
  // Library/Preferences, 用户偏好设置,会同步iTunes
  public static var preferences: String {
    return NSSearchPathForDirectoriesInDomains(.preferencePanesDirectory, .userDomainMask, true).first!
  }
  
  public static var library: String {
    return NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first!
  }
  
  // 临时文件,会自动清理
  public static var tmp: String {
    return NSTemporaryDirectory()
  }
}

// MARK: - log

extension SJApp {
  
  /// 自定义DEBUG打印
  ///
  /// - Parameters:
  ///   -  message: 打印的内容
  ///   - filename: 打印所在文件
  ///   - function: 打印所在方法
  ///   -     line: 打印所在行数
  public static func log(_ item: Any, filename: String = #file, function: StaticString = #function, line: Int = #line) {
    #if DEBUG
      print("\n")
      let filenameWithoutExtension = filename.sj.lastPathComponent
      let log = "file: \(filenameWithoutExtension)\nline: \(line)\nfunc: \(function)\nlog : \(item)"
      print(log)
      print("\n= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =\n")
    #endif
  }
  
  public static func functionKey(functuon: StaticString = #function) -> String {
    return "swxc.\(functuon)"
  }
}

// MARK: - layout

extension SJApp {
  
  public static var navBarHeight: CGFloat = 64.0
  public static var tabBarHeight: CGFloat = 44.0
  
  public static var tableViewFrame: CGRect {
    return CGRect(x: 0, y: 0, width: UIScreen.width, height: UIScreen.height - SJApp.tabBarHeight)
  }
  
  public static func bounds(width: CGFloat, height: CGFloat) -> CGRect {
    return CGRect(x: 0, y: 0, width: width, height: height)
  }
}

extension SJApp {
  
  public static func showStateBarHUD() {
    UIApplication.shared.isNetworkActivityIndicatorVisible = true
  }
  
  public static func hideStateBarHUD() {
    UIApplication.shared.isNetworkActivityIndicatorVisible = false
  }
  
  public static var isShowHUD: Bool {
    for subView in SJApp.keyWindow.subviews {
      if subView.isKind(of: MBProgressHUD.self) {
        return true
      }
    }
    return false
  }
  
  public static func showHUD() {
    if SJApp.isShowHUD { return }
    
    let hud = MBProgressHUD.showAdded(to: SJApp.keyWindow, animated: true)
    hud.backgroundView.style = .solidColor
    hud.backgroundView.color = GlobalConfig.BGLightGreyColor
    hud.bezelView.backgroundColor = UIColor.white
    hud.contentColor = GlobalConfig.BGSkyBlueColor
    
  }
  
  public static func showHUD(in view: UIView) {
    if SJApp.isShowHUD { return }
    
    let hud = MBProgressHUD.showAdded(to: view, animated: true)
    hud.backgroundView.style = .solidColor
    hud.backgroundView.color = GlobalConfig.BGLightGreyColor
    hud.bezelView.backgroundColor = UIColor.white
    hud.contentColor = GlobalConfig.BGSkyBlueColor
  }
    
    public static func showClearHUD() {
        if SJApp.isShowHUD { return }
        let hud = MBProgressHUD.showAdded(to: SJApp.keyWindow, animated: true)
        hud.backgroundView.style = .solidColor
        hud.backgroundView.color = UIColor.clear
        hud.bezelView.backgroundColor = UIColor.white
        hud.contentColor = GlobalConfig.BGSkyBlueColor
    }
  
    public static func hideHUD(in view: UIView) {
        runOnMainThread {
            MBProgressHUD.hide(for: view, animated: true)
        }
    }
  
    public static func hideHUD() {
        runOnMainThread {
            MBProgressHUD.hide(for: SJApp.keyWindow, animated: true)
        }
    }
  
    public static func hideProgressHUD() {
        runOnMainThread {
            MBProgressHUD.hide(for: SJApp.keyWindow, animated: true)
        }
    }
  
    public static func endEdit() {
        SJApp.keyWindow.endEditing(true)
    }
  
    public static func openSet() {
        guard let setUrl = URL(string: UIApplicationOpenSettingsURLString) else {
            return
        }
        
        if UIApplication.shared.canOpenURL(setUrl) {
          UIApplication.shared.openURL(setUrl)
        }
    }
    
    // 网络权限
    public static var isAlowNetWork: Bool {
        var isAlow = false
        if #available(iOS 9.0, *) {
            let cellularData = CTCellularData()
            let state = cellularData.restrictedState
            switch state {
                // 有网
            case .notRestricted:
                isAlow = true
                // 无网
            case .restricted, .restrictedStateUnknown:
                isAlow = false
            }
        }
        return isAlow
    }

}
